package com.xtc.netty.io.nio.buffer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BufferDemo {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("C:\\Users\\Administrator\\Desktop\\百度网盘会员\\bufferDemo.txt");

            FileChannel channel = file.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            output("初始化",buffer);

            // 先读一下
            channel.read(buffer);
            output("调用read()", buffer);

            // 准备操作之前，先先锁定范围
            buffer.flip();
            output("调用flip()", buffer);

            while (buffer.remaining() > 0) {
                buffer.get();
            }
            output("调用get()", buffer);

            // 可以理解为解锁
            buffer.clear();
            output("调用clear()", buffer);

            channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void output(String step, ByteBuffer buffer) {
        System.out.println(step + ":");
        // 容量，数组大小
        System.out.print("capacity: " + buffer.capacity() + ",");

        // 当前操作数据所在位置
        System.out.print("position: " + buffer.position() + ",");

        // 数据操作范围，只能是position ~ limit之间
        System.out.println("limit: " + buffer.limit() + ",");

        System.out.println();
    }
}
